package cn.aj.system.service.impl;

import cn.aj.system.domain.Menu;
import cn.aj.system.mapper.MenuMapper;
import cn.aj.system.service.IMenuService;
import cn.aj.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author aj
 * @since 2022-11-29
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {

    @Autowired
    private MenuMapper menuMapper;

    /**
    * @Title: first
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/11/29 0029 21:45
    * @Parameters: []
    * @Return java.util.List<cn.aj.system.domain.Menu>
     *     父级菜单业务
    */
    @Override
    public List<Menu> first() {
        List<Menu> loadAll = super.loadAll();
        // 过滤为null
        return loadAll.stream().filter(load->null==load.getParentId()).collect(Collectors.toList());
    }


    /**
    * @Title: tree
    * @Description: TODO
    * @Author: Mr.GT
    * @Version: 1.0
    * @Date:  2022/11/30 0030 16:41
    * @Parameters: []
    * @Return java.util.List<cn.aj.system.domain.Menu>
     *     无限极树
    */
    @Override
    public List<Menu> tree() {
        List<Menu> menusList = menuMapper.tree();
        // list转map
      //  Map<Long, Menu> menuMap = menusList.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        ArrayList<Menu> list = new ArrayList<Menu>(); // 创建新装tree
        for (Menu menu : menusList) { // 先遍历, 把所有的爹找出来
            if(menu.getParentId() == null){ // 添加
                list.add(menu);
            } else {
                // 找儿子
                for (Menu children : menusList) {
                    if(children.getId().equals(menu.getParentId())) {
                        children.getChildren().add(menu);
                        break;
                    }
                }
            }
        }

        return list;
    }
}
